package com.itheima.reggie.web;

import org.apache.commons.lang.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.pojo.Employee_员工信息;
import com.itheima.reggie.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * @Author: cl
 * @Date: 2022/4/2 - 04 - 02
 * @Description:
 */
@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;


    //用户登录
    @PostMapping("/login")
    public R<Employee_员工信息> login(HttpServletRequest request, @RequestBody Employee_员工信息 employee) {

        //1、将页面提交过来的密码加密处理
        String password = employee.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());

        //2、根据页面提交的用户名查询数据库
        Employee_员工信息 emp = employeeService.getOne(
                Wrappers.<Employee_员工信息>lambdaQuery().eq(
                        Employee_员工信息::getUsername, employee.getUsername()
                )
        );

        //3、判断emp是否为空
        if (emp == null) {
            return R.error("用户名不存在！");
        }

        //4、判断密码是否正确
        if (!emp.getPassword().equals(password)) {
            return R.error("密码输入有误！");
        }

        //5、查询员工状态是否为禁用
        if (emp.getStatus() == 0) {
            return R.error("账号已被禁用！");
        }

        //6、登录成功，将员工的id放入session中并返回结果
        //注意要用从数据库查出来的对象，不能用用户输入的  因为用户没输入Id
        request.getSession().setAttribute("employee", emp.getId());
        return R.success(emp);
    }

    //用户退出
    @PostMapping("logout")
    public R<String> logout(HttpServletRequest request) {
        //退出需要清理session中的永和Id
        request.getSession().removeAttribute("employee");
        //或者直接销毁session
        request.getSession().invalidate();
        return R.success("退出成功！");
    }

    //新增员工
    @PostMapping()
    public R<String> save(HttpServletRequest request, @RequestBody Employee_员工信息 employee) {
        log.info("新增员工，员工信息：{}", employee);

        //把前端没有输入的信息添加上去

        //给密码加密，密码前端没输入默认为123456
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));

//        employee.setCreateTime(LocalDateTime.now());
//        employee.setUpdateTime(LocalDateTime.now());
//
//        //获取当前用户的id
//        Long empId = (Long) request.getSession().getAttribute("employee");
//
//        employee.setCreateUser(empId);
//        employee.setUpdateUser(empId);

        employeeService.save(employee);
        return R.success("新增员工成功！");

    }

    //分页查询员工
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name) {
        log.info("page = {},pageSize = {},name = {}", page, pageSize, name);

        //构造分页构造器
        Page pageInfo = new Page(page, pageSize);

        //构造条件构造器
        //LambdaQueryWrapper<Employee> queryWrapper = Wrappers.lambdaQuery();
        LambdaQueryWrapper<Employee_员工信息> queryWrapper = new LambdaQueryWrapper<>();

        //System.out.println(StringUtils.isNotEmpty(name)+"-----------------------");
        if(name!=null){
            name = name.trim();
        }
        //添加过滤条件
        queryWrapper.like(StringUtils.isNotEmpty(name), Employee_员工信息::getName, name);

        //添加排序条件
        queryWrapper.orderByAsc(Employee_员工信息::getUpdateTime);


        //执行SQL
        employeeService.page(pageInfo, queryWrapper);

        return R.success(pageInfo);
    }

    /**
     * 根据id修改员工信息
     *
     * @param employee
     * @return
     */
    @PutMapping
    public R<String> update(HttpServletRequest request, @RequestBody Employee_员工信息 employee) {
        log.info(employee.toString());
//
//        Long empId = (Long) request.getSession().getAttribute("employee");
//
//        //设置更新时间
//        employee.setUpdateTime(LocalDateTime.now());
//        //设置更新人员ID
//        employee.setUpdateUser(empId);

        employeeService.updateById(employee);
        return R.success("员工信息已修改！");

    }

    /**
     * 根据id查询员工信息
     *
     * @param id
     * @return
     */
    @GetMapping("{id}")
    public R<Employee_员工信息> getById(@PathVariable Long id) {
        log.info("根据id查询");

        Employee_员工信息 emp = employeeService.getById(id);
        if (emp != null) {
            return R.success(emp);
        }
        return R.error("员工不存在！");
    }


}
